package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    //处理查询所有部门的请求
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Role> result = roleService.query(qo);
        model.addAttribute("result", result);
        return "role/list";//找视图/WEB-INF/views/role/list,jsp
    }

    //处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                roleService.delete(id);
            }
            return new JsonResult(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "操作失败");
        }

    }

    // 去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id, Model model) {

        //查询所有权限,存到模型中
        model.addAttribute("permissions", permissionService.listAll());

        if (id != null) {//表示去修改
            //通过id去查询角色
            Role role = roleService.get(id);
            model.addAttribute("role", role);

        }
        return "role/input";//让浏览器重新发送一次请求

    }


    //修改或新增
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() == null) {
            roleService.save(role,ids); // 新增
        } else {
            roleService.update(role,ids);//修改
        }
        return "redirect:/role/list.do";//让浏览器重新发一次请求

    }
}

